package com.lanju.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;

public class MessageUtil {
	/**
	 * 使用dom4j将请求流中的xml转成map
	 * @param is
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> toMap(InputStream is ) throws DocumentException, IOException{
		if(is ==null) return null;
		//获取SAXReader
		SAXReader reader=new SAXReader();
		//获取文档
		Document doc=reader.read(is);
		//获取根元素
		Element root=doc.getRootElement();
		//获取其他元素
		List<Element> elements=root.elements();
		//遍历封装到Map
		Map<String,String> map=new HashMap<String, String>();
		for(Element e: elements){
			map.put(e.getName(), e.getText());
		}
		is.close();
		return map;
	}
	/**
	 * 将map中的数据封装成Messgae
	 * @param map
	 * @return
	 */
	public static Message toMessage(Map<String,String> map){
		Message message=new Message();
		message.setContent(map.get("Content"));
		message.setCreateTime(Integer.valueOf(map.get("CreateTime")));
		message.setFromUserName(map.get("FromUserName"));
		message.setMsgId(map.get("MsgId"));
		message.setToUserName(map.get("ToUserName"));
		message.setMsgType(map.get("MsgType"));
		return message;
		
	}
	/**
	 * 将对象转成xml
	 * @param message
	 * @return
	 */
	public static String toXml(Message message){
		//实例化AStream
		XStream stream=new XStream();
		stream.alias("xml", message.getClass());
		return stream.toXML(message);
		
	}
	
	/**
     * XML格式字符串转换为Map
     *
     * @param request
     * @param response
     * @return XML数据转换后的Map
     * @throws Exception
     */ 
    public static Map<String, String> parseXml(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 将解析结果存储在HashMap中
            Map<String, String> map = new HashMap<String, String>();
            // 从request中取得输入流
            InputStream inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
            // 释放资源
            inputStream.close();
            return map;
        } catch (IOException e) {
        } catch (DocumentException e) {
        }
        return null;
    }
}
